<form *ngIf="!form.initError; else showInitError" [formGroup]="formGroup" class="max-w-50rem host-form">
    <p-fieldset legend="Form Settings">
        <div class="flex flex-column">
            <div class="flex align-items-center">
                <p-inputSwitch
                    ngDefaultControl
                    formControlName="splitFormMode"
                    (onChange)="onSplitModeChange()"
                ></p-inputSwitch>
                <div class="flex ml-2">Configure individual server values.</div>
            </div>
            <div class="flex align-items-center mt-2">
                <p-inputSwitch ngDefaultControl formControlName="globalReservation"></p-inputSwitch>
                <div class="flex ml-2">Global reservation.</div>
            </div>
        </div>
    </p-fieldset>
    <p-fieldset legend="Assignments" styleClass="host-form-section">
        <div>
            <span class="p-float-label">
                <p-multiSelect
                    inputId="servers-select"
                    optionLabel="label"
                    optionValue="id"
                    [options]="form.filteredDaemons"
                    formControlName="selectedDaemons"
                    display="chip"
                    [showToggleAll]="false"
                    styleClass="adaptive-chips-background w-full"
                    (onChange)="onDaemonsChange()"
                >
                </p-multiSelect>
                <label for="servers-select">DHCP Servers</label>
            </span>
            <small
                *ngIf="
                    formGroup.get('selectedDaemons').invalid &&
                    (formGroup.get('selectedDaemons').dirty || formGroup.get('selectedDaemons').touched)
                "
                class="p-error block"
                >At least one server must be selected.
            </small>
        </div>
        <div *ngIf="!formGroup.get('globalReservation').value">
            <span class="p-float-label">
                <p-dropdown
                    inputId="subnets-dropdown"
                    optionLabel="subnet"
                    optionValue="id"
                    [autoDisplayFirst]="false"
                    [options]="form.filteredSubnets"
                    formControlName="selectedSubnet"
                    [showClear]="true"
                    styleClass="w-full"
                    (onChange)="onSelectedSubnetChange()"
                >
                </p-dropdown>
                <label for="subnets-dropdown">Subnet</label>
            </span>
            <small
                *ngIf="
                    formGroup.controls['selectedSubnet'].invalid &&
                    (formGroup.controls['selectedSubnet'].dirty || formGroup.controls['selectedSubnet'].touched)
                "
                class="p-error block"
                >Subnet must be selected if the reservation is not global.
            </small>
        </div>
    </p-fieldset>

    <p-fieldset legend="DHCP Identifier" styleClass="host-form-section">
        <div formGroupName="hostIdGroup" class="grid">
            <div class="col-6 sm:col-3">
                <p-dropdown
                    [options]="hostIdTypes"
                    formControlName="idType"
                    styleClass="w-full"
                    (onChange)="onSelectedIdentifierChange()"
                >
                </p-dropdown>
            </div>
            <div class="col-6 sm:col-3">
                <p-dropdown [options]="hostIdFormats" formControlName="idFormat" styleClass="w-full"> </p-dropdown>
            </div>

            <div
                *ngIf="formGroup.get('hostIdGroup.idFormat').value === 'hex'; else hostIdFormatText"
                class="col-12 sm:col-6"
            >
                <input pInputText formControlName="idInputHex" class="w-full" placeholder="e.g. 01:02:03:04:05:06" />
                <small
                    *ngIf="
                        formGroup.get('hostIdGroup.idInputHex').invalid &&
                        (formGroup.get('hostIdGroup.idInputHex').dirty ||
                            formGroup.get('hostIdGroup.idInputHex').touched)
                    "
                    class="p-error block"
                    >{{
                        formGroup.get('hostIdGroup.idInputHex').hasError('pattern')
                            ? 'Please specify valid hexadecimal digits (e.g., ab:09:ef:01).'
                            : formGroup.get('hostIdGroup.idInputHex').hasError('maxlength')
                              ? formGroup.get('hostIdGroup.idInputHex').errors['maxlength']
                              : 'DHCP identifier is required.'
                    }}
                </small>
            </div>
            <ng-template #hostIdFormatText>
                <div class="col-12 sm:col-6">
                    <input
                        pInputText
                        formControlName="idInputText"
                        class="w-full"
                        placeholder="text identifier format"
                    />
                    <small
                        *ngIf="
                            formGroup.get('hostIdGroup.idInputText').invalid &&
                            (formGroup.get('hostIdGroup.idInputText').dirty ||
                                formGroup.get('hostIdGroup.idInputText').touched)
                        "
                        class="p-error block"
                        >{{
                            formGroup.get('hostIdGroup.idInputText').hasError('maxlength')
                                ? 'The identifier length exceeds the maximum value of ' +
                                  formGroup.get('hostIdGroup.idInputText').errors['maxlength'].requiredLength +
                                  '.'
                                : 'DHCP identifier is required.'
                        }}
                    </small>
                </div>
            </ng-template>
        </div>
    </p-fieldset>

    <p-fieldset legend="Host Reservations" styleClass="host-form-section">
        <div>
            <span class="p-float-label">
                <input id="hostname-input" pInputText class="w-full" formControlName="hostname" />
                <label for="hostname-input">Hostname</label>
            </span>
            <small
                *ngIf="
                    formGroup.get('hostname').invalid &&
                    (formGroup.get('hostname').dirty || formGroup.get('hostname').touched)
                "
                class="p-error block"
                >Please specify a valid hostname (e.g., alice-laptop or bob.example.org.).
            </small>
        </div>
        <div class="grid">
            <ng-container formArrayName="ipGroups">
                <ng-container *ngFor="let ipGroup of ipGroups.controls; index as i">
                    <ng-container [formGroup]="ipGroup" class="flex align-items-start">
                        <div class="col-12 sm:col-3">
                            <p-dropdown [options]="ipTypes" formControlName="ipType" styleClass="w-full"> </p-dropdown>
                        </div>
                        <ng-container [ngSwitch]="ipGroup.value.ipType">
                            <ng-container *ngSwitchCase="'ipv4'">
                                <div class="col-10 sm:col-8">
                                    <input
                                        *ngSwitchCase="'ipv4'"
                                        pInputText
                                        formControlName="inputIPv4"
                                        class="w-full"
                                        [placeholder]="ipv4Placeholder"
                                    />
                                    <small
                                        *ngIf="
                                            ipGroup.get('inputIPv4').invalid &&
                                            (ipGroup.get('inputIPv4').dirty || ipGroup.get('inputIPv4').touched)
                                        "
                                        class="p-error block"
                                    >
                                        {{
                                            ipGroup.get('inputIPv4').hasError('ip-subnet-range')
                                                ? ipGroup.get('inputIPv4').errors['ip-subnet-range']
                                                : 'Please specify a valid IPv4 address.'
                                        }}
                                    </small>
                                </div>
                                <ng-container *ngTemplateOutlet="ipDeleteButton"></ng-container>
                            </ng-container>
                            <ng-container *ngSwitchCase="'ia_na'">
                                <div class="col-10 sm:col-8">
                                    <input
                                        *ngSwitchCase="'ia_na'"
                                        pInputText
                                        formControlName="inputNA"
                                        class="w-full"
                                        [placeholder]="ipv6Placeholder"
                                    />
                                    <small
                                        *ngIf="
                                            ipGroup.get('inputNA').invalid &&
                                            (ipGroup.get('inputNA').dirty || ipGroup.get('inputNA').touched)
                                        "
                                        class="p-error block"
                                    >
                                        <ng-container
                                            *ngIf="
                                                ipGroup.get('inputNA').hasError('ip-subnet-range');
                                                else elseInputNAHasErrorBlock
                                            "
                                        >
                                            {{ ipGroup.get('inputNA').errors['ip-subnet-range'] }}
                                        </ng-container>
                                        <ng-template #elseInputNAHasErrorBlock>
                                            <ng-container>Please specify a valid IPv6 address.</ng-container>
                                        </ng-template>
                                    </small>
                                </div>
                                <ng-container *ngTemplateOutlet="ipDeleteButton"></ng-container>
                            </ng-container>
                            <ng-container *ngSwitchCase="'ia_pd'">
                                <div class="col-6">
                                    <input
                                        pInputText
                                        formControlName="inputPD"
                                        class="w-full"
                                        placeholder="e.g. 3000:1::"
                                    />
                                </div>
                                <div class="col-4 sm:col-2">
                                    <p-inputNumber
                                        ngDefaultControl
                                        min="1"
                                        max="128"
                                        inputStyleClass="w-full"
                                        formControlName="inputPDLength"
                                    >
                                    </p-inputNumber>
                                    <small
                                        *ngIf="
                                            ipGroup.get('inputPD').invalid &&
                                            (ipGroup.get('inputPD').dirty || ipGroup.get('inputPD').touched)
                                        "
                                        class="p-error block"
                                        >Please specify a valid IPv6 prefix.
                                    </small>
                                </div>
                                <ng-container *ngTemplateOutlet="ipDeleteButton"></ng-container>
                            </ng-container>
                        </ng-container>
                        <ng-template #ipDeleteButton>
                            <div class="col-2 sm:col-1">
                                <button
                                    pButton
                                    pRipple
                                    type="button"
                                    icon="pi pi-times"
                                    class="mr-2 p-button-rounded p-button-danger p-button-text"
                                    (click)="deleteIPInput(i)"
                                ></button>
                            </div>
                        </ng-template>
                    </ng-container>
                </ng-container>
            </ng-container>
        </div>
        <div>
            <button
                *ngIf="ipGroups.length === 0 || ipTypes.length > 1"
                pButton
                class="p-button-rounded p-button-text mt-2"
                label="Add IP Reservation"
                (click)="addIPInput()"
            ></button>
        </div>
    </p-fieldset>

    <ng-template #splittableFieldsetHeaderTemplate let-configuredName="configuredName" let-i="index">
        <span class="stork-fieldset-legend-text"
            >{{ configuredName }}
            <span
                *ngIf="formGroup.get('splitFormMode').value && selectedDaemons.value?.length >= i + 1"
                class="font-normal"
                >&nbsp;/&nbsp;
                <a
                    routerLink="/apps/{{ form.getDaemonById(selectedDaemons.value[i]).appType }}/{{
                        form.getDaemonById(selectedDaemons.value[i]).appId
                    }}"
                >
                    {{ form.getDaemonById(selectedDaemons.value[i]).label }}
                </a>
            </span>
        </span>
    </ng-template>

    <ng-container *ngIf="!form.dhcpv6" formArrayName="bootFields">
        <ng-container *ngFor="let bootFields of bootFieldsArray.controls; let i = index">
            <p-fieldset
                *ngIf="i === 0 || formGroup.get('splitFormMode').value"
                styleClass="host-form-section"
                [formGroupName]="i"
            >
                <ng-template pTemplate="header">
                    <ng-container
                        *ngTemplateOutlet="
                            splittableFieldsetHeaderTemplate;
                            context: { configuredName: 'Boot Fields', index: i }
                        "
                    ></ng-container>
                </ng-template>
                <div>
                    <span class="p-float-label">
                        <input id="next-server-input-{{ i }}" pInputText class="w-full" formControlName="nextServer" />
                        <label for="next-server-input-{{ i }}">Next Server</label>
                    </span>
                    <small
                        *ngIf="
                            getBootFieldsGroup(i).get('nextServer').invalid &&
                            (getBootFieldsGroup(i).get('nextServer').dirty ||
                                getBootFieldsGroup(i).get('nextServer').touched)
                        "
                        class="p-error block"
                        >Please specify a valid IPv4 address.
                    </small>
                </div>
                <div>
                    <span class="p-float-label">
                        <input
                            id="server-hostname-input-{{ i }}"
                            pInputText
                            class="w-full"
                            formControlName="serverHostname"
                        />
                        <label for="server-hostname-input-{{ i }}">Server Hostname</label>
                    </span>
                    <small
                        *ngIf="
                            getBootFieldsGroup(i).get('serverHostname').invalid &&
                            (getBootFieldsGroup(i).get('serverHostname').dirty ||
                                getBootFieldsGroup(i).get('serverHostname').touched)
                        "
                        class="p-error block"
                        >Please specify a valid hostname (e.g., alice-laptop or bob.example.org.).
                    </small>
                </div>
                <div>
                    <span class="p-float-label">
                        <input
                            id="boot-file-name-input-{{ i }}"
                            pInputText
                            class="w-full"
                            formControlName="bootFileName"
                        />
                        <label for="boot-file-name-input-{{ i }}">Boot File Name</label>
                    </span>
                </div>
            </p-fieldset>
        </ng-container>
    </ng-container>

    <ng-container *ngFor="let clientClassesSet of clientClassesArray.controls; let i = index">
        <p-fieldset *ngIf="i === 0 || formGroup.get('splitFormMode').value" styleClass="host-form-section">
            <ng-template pTemplate="header">
                <ng-container
                    *ngTemplateOutlet="
                        splittableFieldsetHeaderTemplate;
                        context: { configuredName: 'Client Classes', index: i }
                    "
                ></ng-container>
            </ng-template>
            <div>
                <app-dhcp-client-class-set-form
                    [clientClasses]="form.clientClasses"
                    [classFormControl]="clientClassesSet"
                ></app-dhcp-client-class-set-form>
            </div>
        </p-fieldset>
    </ng-container>

    <ng-container formArrayName="options">
        <ng-container *ngFor="let optionsSet of optionsArray.controls; let i = index">
            <p-fieldset *ngIf="i === 0 || formGroup.get('splitFormMode').value" styleClass="host-form-section">
                <ng-template pTemplate="header">
                    <ng-container
                        *ngTemplateOutlet="
                            splittableFieldsetHeaderTemplate;
                            context: { configuredName: 'DHCP Options', index: i }
                        "
                    ></ng-container>
                </ng-template>
                <div [formGroupName]="i">
                    <app-dhcp-option-set-form
                        [v6]="form.dhcpv6"
                        [formArray]="optionsSet"
                        (optionAdd)="onOptionAdd(i)"
                    ></app-dhcp-option-set-form>
                </div>
            </p-fieldset>
        </ng-container>
    </ng-container>

    <div class="flex align-items-center m-5">
        <p-button
            *ngIf="savedUpdateHostBeginData"
            icon="pi pi-replay"
            label="Revert Changes"
            styleClass="mr-2 p-button-secondary"
            (onClick)="onRevert()"
        ></p-button>
        <p-button label="Cancel" styleClass="mr-2 p-button-secondary" (onClick)="onCancel()"></p-button>
        <p-button label="Submit" [disabled]="formGroup.invalid" (onClick)="onSubmit()"></p-button>
        <app-help-tip subject="Host Reservation Submission">
            <p>
                Submitted host reservation is created in Kea and may appear in Stork with a delay. Try to refresh the
                list of host reservations after submission to see the new reservation.
            </p>
        </app-help-tip>
    </div>
</form>
<ng-template #showInitError>
    <p-fieldset legend="Errors" styleClass="mt-4">
        <div class="max-w-40rem">
            <p-messages severity="error">
                <ng-template pTemplate>
                    <div class="flex flex-column">
                        <div class="flex align-items-center m-4">
                            In order to apply configuration changes, the server should begin a transaction between the
                            user and the server. The server should also return current data required in the form where
                            the host information is specified. Unfortunately, starting the new transaction failed with
                            the following error:
                        </div>
                        <div class="flex align-items-center m-4 font-italic">
                            {{ form.initError }}
                        </div>
                        <div class="flex align-items-center m-4">Retrying can help in some cases.</div>
                    </div>
                </ng-template>
            </p-messages>
            <div class="mt-3">
                <p-button label="Retry" (onClick)="onRetry()"></p-button>
            </div>
        </div>
    </p-fieldset>
</ng-template>
